﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    /// <summary>
    /// 单元格内按钮组件
    /// </summary>
    public class TableCellButtonItem<TItem> : Button
    {
        /// <summary>
        /// 获得/设置 当前行绑定数据
        /// </summary>
        [Parameter]
        public TItem? Item { get; set; }

        /// <summary>
        /// 获得/设置 按钮点击后的回调方法
        /// </summary>
        [Parameter]
        public Func<TItem, Task>? OnClickCallback { get; set; }

        /// <summary>
        /// 获得/设置 OnClick 事件不刷新父组件
        /// </summary>
        [Parameter]
        public Func<TItem, Task>? OnClickWithoutRenderItem { get; set; }


        [Parameter]
        public string LoadingText { set; get; } = "...";


        /// <summary>
        /// OnInitialized 方法
        /// </summary>
        protected override void OnInitialized()
        {
            Size = Size.ExtraSmall;
            base.OnInitialized();

            if (AdditionalAttributes == null)
            {
                AdditionalAttributes = new Dictionary<string, object>();
            }

            if (!AdditionalAttributes.TryGetValue("type", out var _))
            {
                AdditionalAttributes["type"] = "button";
            }

            ButtonIcon = Icon;

            OnClickButton = EventCallback.Factory.Create<MouseEventArgs>(this, async e =>
            {
                if (IsAsync)
                {
                    ButtonIcon = LoadingIcon;
                    IsDisabled = true;
                }
                if (Item != null && OnClickCallback != null) await OnClickCallback.Invoke(Item);
                if (OnClickWithoutRenderItem != null)
                {
                    await OnClickWithoutRenderItem.Invoke(Item);
                }
                if (OnClick.HasDelegate)
                {
                    await OnClick.InvokeAsync(e);
                }
                if (IsAsync)
                {
                    ButtonIcon = Icon;
                    IsDisabled = false;
                }
            });
        }
    }
}
